#include "docviewer.h"
#include "docentity.h"
DocViewer::DocViewer(DbConnection *DB, QWidget *Parent) :
    QWidget(Parent),m_tree(DB,this),
    m_view(0), m_last(0), m_addMC(0),m_hlButton(0),
    m_history(this),oldPosition("1"), m_messenger(DB, this),
    m_reminder(this), m_timer(parent()), m_refButton(0)
{
    connect(&m_tree,SIGNAL(state_message(QString,int,QColor)),this,SIGNAL(state_message(QString,int,QColor)));
    connect(&m_tree,SIGNAL(state_message(QString,int)),this,SIGNAL(state_message(QString,int)));
    connect(&m_tree,SIGNAL(childWakeUp(DocEntity*)),this,SLOT(setView(DocEntity*)));
    connect(&m_history,SIGNAL(itemChange(DocEntity*)),this,SLOT(setView(DocEntity*)));
    connect(&m_tree,SIGNAL(filterWasChange()),this,SLOT(onFilterChange()));
    connect(&m_messenger,SIGNAL(messageDoubleClicked(QString)),&m_tree,SLOT(itemByFID(QString)));
    connect(&m_messenger,SIGNAL(newMessages(QString)),&m_reminder,SLOT(setMessage(QString)));
    connect(&m_timer,SIGNAL(timeout()),&m_messenger,SLOT(loadMessages()));
    connect(&m_timer,SIGNAL(timeout()),this,SLOT(onTimeOut()));
    connect(&m_reminder,SIGNAL(mouseClick()),&m_messenger,SLOT(show()));
    connect(&m_tree,SIGNAL(wasRefreshItem()),this,SLOT(onWasRefreshItem()));
    QVBoxLayout* main = new QVBoxLayout;
    m_splitter = new QSplitter(this);
    m_splitter->addWidget(&m_tree);
    QWidget* right_panel = new QWidget;
    m_layout= new QVBoxLayout;
    m_layout->setAlignment(Qt::AlignTop);
    m_layout->setContentsMargins(0,0,0,0);
    right_panel->setLayout(m_layout);
    m_splitter->addWidget(right_panel);
    main->addWidget(m_splitter);
    m_refButton = new QAction(QIcon(":/refresh"),tr("Обновить все"),this);
    connect(m_refButton,SIGNAL(triggered()),&m_tree,SLOT(refresh()));
    m_saveButton = new QAction(QIcon(":/save_entity"),tr("Сохранить все"),this);
    setLayout(main);
    m_messenger.loadMessages();
}
void DocViewer::addMacAction()
{
    m_tree.appendMacAction(false);
}
void DocViewer::setHighlighterOn(const bool &on)
{
    m_tree.setHighlight(on);
}
void DocViewer::addInnerMacAction()
{
    m_tree.appendMacAction(true);
}
void DocViewer::setCommonNumering(const bool &commonNumering)
{
    m_tree.setCommonNumbering(commonNumering);
}
bool DocViewer::highlight() const
{
    return m_tree.highlight();
}
QAction* DocViewer::filterButton()
{
    QAction* action = new QAction(QIcon(":/filter"),tr("Фильтры"),parent());
    QMenu* menu = new QMenu;
    menu->addActions(m_tree.filter(TreeDoc::Scope));
    menu->addSeparator();
    menu->addActions(m_tree.filter(TreeDoc::State));
    action->setMenu(menu);
    return action;
}
QAction* DocViewer::messengerButton()
{
    QAction* action = new QAction(QIcon(":/messenger"),tr("Сообщения"),parent());
    connect(action,SIGNAL(triggered()),&m_messenger,SLOT(readMessages()));
    return action;
}
QAction* DocViewer::highlighterButton()
{
    if(m_hlButton!=0) delete m_hlButton;
    m_hlButton = new QAction(parent());
    if(m_tree.highlight())
    {
        m_hlButton->setIcon(QIcon(":/on"));
        m_hlButton->setText(tr("Выключить подсветку"));
    }
    else
    {
        m_hlButton->setIcon(QIcon(":/off"));
        m_hlButton->setText(tr("Включить подсветку"));
    }
    connect(m_hlButton,SIGNAL(triggered()),this,SLOT(onHighlighterOn()));
    return m_hlButton;
}
void DocViewer::onHighlighterOn()
{
    if(m_hlButton==0)return;
    m_tree.setHighlight(!m_tree.highlight());
    if(m_tree.highlight())
    {
        m_hlButton->setIcon(QIcon(":/on"));
        m_hlButton->setText(tr("Выключить подсветку"));
    }
    else
    {
        m_hlButton->setIcon(QIcon(":/off"));
        m_hlButton->setText(tr("Включить подсветку"));
    }
}

QAction* DocViewer::addMCButton()
{
    if(m_addMC!=0) delete m_addMC;
    m_addMC = new QAction(QIcon(":/add_entity"),tr("Добавить %1 КД/ПД"),parent());
    connect(m_addMC,SIGNAL(triggered()),this,SLOT(onActionExecute()));
    m_addMC->setObjectName(oldPosition);
    QMenu* menu = new QMenu;
    m_addMC->setMenu(menu);
    QActionGroup* group = new QActionGroup(parent());
    QAction* action = new QAction(tr("общезаводские"),parent());
    action->setCheckable(true);
    action->setObjectName("1");
    if(oldPosition=="1")
    {
        action->setChecked(true);
        m_addMC->setText(m_addMC->text().arg(action->text()));
    }
    group->addAction(action);
    menu->addAction(action);
    action = new QAction(tr("внутри подразделений"),parent());
    action->setCheckable(true);
    group->addAction(action);
    action->setObjectName("2");
    if(oldPosition=="2")
    {
        m_addMC->setText(m_addMC->text().arg(action->text()));
        action->setChecked(true);
    }
    menu->addAction(action);
    group->setExclusive(true);
    connect(group,SIGNAL(triggered(QAction*)),this,SLOT(onActionMenuChange(QAction*)));
    return m_addMC;
}
void DocViewer::onActionMenuChange(QAction *action)
{
     m_addMC->setObjectName(action->objectName());
     oldPosition=action->objectName();
     m_addMC->setText(tr("Добавить %1 КД/ПД").arg(action->text()));
}
void DocViewer::onActionExecute()
{
    m_tree.appendMacAction(m_addMC->objectName()=="2");
    m_tree.filter(TreeDoc::Scope).at(m_addMC->objectName().toInt()-1)->trigger();
}
bool  DocViewer::initialization()
{
   onFilterChange();
   return m_tree.initialization();
}

QSplitter* DocViewer::splitter()
{
    return m_splitter;
}

void DocViewer::setHistoryMaxSize(const int &maxSize)
{
    m_history.setMaxSize(maxSize);
}
void DocViewer::setView(DocEntity *item)
{
    if(m_last==item) return;
    if(item->childCount()==0) item->giveBithTo();
    m_tree.setCurrentItem(item);
    m_history.setCurrent(item);
    setWidget(item->view());
    m_last=item;
    QList<QAction*> tools;
    tools.append(addMCButton());
    tools.append(m_history.back());
    tools.append(m_history.forward());
    tools.append(m_refButton);
//    tools.append(m_saveButton);
    tools.append(filterButton());
    DocEntity* node =item;
//    while(node!=0)
//    {
        int i=5;
        if(node->operations()->list().count()>0)
        {
            QAction* spr = new QAction(node);
            spr->setSeparator(true);
            tools.insert(i,spr);
            i++;
        }
        foreach(QAction* action, node->operations()->list())
        {
            tools.insert(i,action);
            i++;
        }
//        node=node->parent();
//    }
    QAction* spr = new QAction(node);
    spr->setSeparator(true);
    tools.append(spr);
    tools.append(messengerButton());
    tools.append(highlighterButton());
    emit toolBarChange(tools);
}
void DocViewer::onFilterChange()
{
    m_history.clear();
    QWidget *view = new QWidget(this);
    QVBoxLayout* main = new QVBoxLayout;
    main->addStretch();
    main->addWidget(new QLabel(tr(""),view));
    main->addStretch();
    main->setAlignment(Qt::AlignCenter);
    view->setLayout(main);
    setWidget(view);
    m_last=0;
    QList<QAction*> tools;
    tools.append(addMCButton());
    tools.append(m_history.back());
    tools.append(m_history.forward());
    tools.append(m_refButton);
    tools.append(filterButton());
    QAction* spr = new QAction(parent());
    spr->setSeparator(true);
    tools.append(spr);
    tools.append(messengerButton());
    tools.append(highlighterButton());
    emit toolBarChange(tools);
}
void DocViewer::setWidget(QWidget *widget)
{
    if(m_view!=0)
    {
        m_layout->removeWidget(m_view);
        delete m_view;
    }
    m_view=widget;
    m_layout->addWidget(widget);

}
void DocViewer::setRefreshInterval(const int &interval)
{
    m_timer.setInterval(interval*60000);
    m_timer.start();
}
void DocViewer::onWasRefreshItem()
{
    m_last=0;
}
void DocViewer::onTimeOut()
{
    m_timer.stop();
    m_tree.refresh();
    m_timer.start();
}
bool DocViewer::isWasChangedItem() const
{
    return m_tree.isWasChangedItems();
}
